<template>
  <div class="learn">
    <div>
    <div class="box1">
      <video
        id="videoCamera"
        class="canvas"
        :width="videoWidth"
        :height="videoHeight"
        autoPlay
      ></video>
      <canvas
        id="canvasCamera"
        class="canvas"
        :width="canvasWidth"
        :height="canvasHeight"
      ></canvas>
    </div>
  </div>
    <Warn v-if="showWarn" @close="showWarn=false" />
      <div class="main">
          <div class="main-left">
              <div class="left-back" @click="goBack">
                  <img src="../static/icons/back.png" />
                  后退
              </div>
              <div class="left-main">
                  <div class="left-title">
                      <img src="../static/icons/memory.png" />
                      学习模式
                  </div>
                  <div class="left-counter">
                      <div class="left-number" style="color:#AAAAAA">{{wordLeft}}</div>
                      <span>剩余</span>
                      <img src="../static/icons/next.png" />
                      <div class="left-number" style="color:#EACD76">{{wordReview}}</div>
                      <span>需巩固</span>
                      <img src="../static/icons/next.png" />
                      <div class="left-number" style="color:#23B26D">{{wordFinished}}</div>
                      <span>已完成</span>
                  </div>
                  <div class="left-rate">{{progress}}%</div>
              </div>
          </div>
          <div class="learn-word">
              <div class="word-card" @click="cardClicked">
                  <div class="card-progress">
                      <div :style="'width:'+unitProgress+'%'" />
                  </div>
                  <div class="word-en"><div/><span>{{wordEn}}</span></div>
                  <div class="word-zh" :style="showZh?'':'opacity:0'">{{wordZh}}</div>
              </div>
              <div class="word-choice">
                  <template v-if="wordType==='new'">
                    <div
                      v-if="wait"
                      class="button new"
                      @click="learnCurrentWord"
                      :style="showZh?'':'border:solid 2px #c0cace;color:#c0cace;'"
                    >
                        <div class="button-num"><span>1</span></div>
                        知道啦，学习下一个
                    </div>
                    <div v-if="xzda"
                      class="button new"
                      @click="cardClicked"
                      :style="showZh?'':'border:solid 2px #c0cace;color:#c0cace;'"
                    ><div class="button-num"><span>1</span></div>
                        点击寻找答案啦
                    </div>
                    <div v-if="dengdai"
                      class="button new"
                      :style="showZh?'':'border:solid 2px #c0cace;color:#c0cace;'"
                    ><div class="button-num"><span>1</span></div>
                        花点时间记住才能进入下一题哦
                    </div>
                  </template>
                  <template v-if="wordType==='learned'">
                      <div
                        class="button green"
                        @click="reviseCurrentWord(1)"
                        :style="showZh?'':'border:solid 2px #c0cace;color:#c0cace;'"
                      >
                          <div class="button-num"><span>1</span></div>
                          我记住啦
                      </div>
                      <div
                        class="button yellow"
                        @click="reviseCurrentWord(2)"
                        :style="showZh?'':'border:solid 2px #c0cace;color:#c0cace;'"
                      >
                          <div class="button-num"><span>2</span></div>
                          有点模糊
                      </div>
                      <div
                        class="button red"
                        @click="reviseCurrentWord(3)"
                        :style="showZh?'':'border:solid 2px #c0cace;color:#c0cace;'"
                      >
                          <div class="button-num"><span>3</span></div>
                          我不太会
                      </div>
                  </template>
              </div>
          </div>
      </div>
  </div>
</template>

<script>
import cn from '@/api/cn'
import Warn from '@/components/Warn'
import axios from 'axios'

export default {
name: 'math',
components: {
  Warn
},
data () {
  return {
    // time part
    wait: false,
    xzda: true,
    dengdai: false,
    os: false, //控制摄像头开关
    thisVideo: null,
    thisContext: null,
    thisCancas: null,
    imgSrc: "",
    videoWidth: 500,
    videoHeight: 400,
    canvasWidth:500,
    canvasHeight:400,
    showWarn: false,
    showZh: false,
    wordUnit: [],
    unitPointer: 0,
    wordLeft: 0, // 剩余
    wordReview: 0, // 需复习
    wordFinished: 0, // 已完成
    wordTotalNum: 0,
    wordList: '',
    wordType: '',
    wordEn: '',
    wordZh: '',
    userName: '', // 当前用户的name
  }
},
created () {
  this.openCamera();
  if (this.$route.query.list) {
    this.wordList = this.$route.query.list// 获得关卡名
    console.log('获得关卡名')
    this.setUserName() // 设置当前用户名
    console.log('设置当前用户名')
    this.wordTotalNum = cn.getListWordNum(this.wordList)
  } else {
    this.$router.go(-1)
  }
},
mounted () {
  this.global.sendcamera = setInterval(this.ongoing, 3000);
  this.global.sendfocus = setInterval(this.sendFocus, 10000);
  setTimeout(() => {
    this.getNextUnit()
    this.setStatusNums()
    cn.reportUserLearned().then(res => console.log(res)) // beta版测试用
  }, 200)
  document.onkeydown = (event) => {
    switch (event.keyCode) {
      case 32: // space
        this.cardClicked()
        break
      case 49: // num 1
        if (this.wordType === 'new') return this.learnCurrentWord()
        this.reviseCurrentWord(1)
        break
      case 50: // num 2
        this.reviseCurrentWord(2)
        break
      case 51: // num 3
        this.reviseCurrentWord(3)
        break
    }
  }
},
computed: {
  progress () { // 这种算法得到的进度不太准
    return (100 * (this.wordReview * 0.3 + this.wordFinished) / this.wordTotalNum).toFixed(2)
  },
  unitProgress () {
    return 100 * ((this.unitPointer / this.wordUnit.length) || 0)
  }
},
beforeDestroy(){
    console.log('离开页面Mt')
    this.stopCamera();
},
methods: {
  ongoing(){
    if(this.global.camerafeedback === 1){
      console.log('摄像头ongoing')
      this.global.camerafeedback = 0
      this.photographBtn();
      this.submitBtn();
    }
    },
    submitBtn() {
      console.log('Into submitBtn');
      var dataToSend = {
          'imgData': this.imgSrc
      };
      var url = this.global.cameraip
      this.$http.post(url +'/api/img', dataToSend).then(res => {
          var focus = JSON.parse(JSON.stringify(res.data))
          this.global.camerafeedback = 1
          if (focus.focus===1) {
            this.global.unfocus += 1
          }else{
            this.global.focus += 1
          }
      });
    },
    openCamera() {
      console.log('Into openCamera')
      this.$nextTick(() => {
        const _this = this;
        this.os = false;
        this.thisCancas = document.getElementById("canvasCamera");
        this.thisContext = this.thisCancas.getContext("2d");
        this.thisVideo = document.getElementById("videoCamera");
        if (navigator.mediaDevices === undefined) {
          navigator.mediaDevices = {};
        }
        if (navigator.mediaDevices.getUserMedia === undefined) {
          navigator.mediaDevices.getUserMedia = function (constraints) {
            let getUserMedia =
              navigator.webkitGetUserMedia ||
              navigator.mozGetUserMedia ||
              navigator.getUserMedia;
            if (!getUserMedia) {
              return Promise.reject(
                new Error("getUserMedia is not implemented in this browser")
              );
            }
            return new Promise(function (resolve, reject) {
              getUserMedia.call(navigator, constraints, resolve, reject);
            });
          };
        }
        const constraints = {
          audio: false,
          video: {
            width: _this.videoWidth,
            height: _this.videoHeight,
            transform: "scaleX(-1)",
          },
        };
        console.log('aboutTo navigator.mediaDevices')
        navigator.mediaDevices.getUserMedia(constraints)
          .then(function (stream) {
            if ("srcObject" in _this.thisVideo) {
              console.log('in _this.thisVideo')
              _this.thisVideo.srcObject = stream;
            } else {
              _this.thisVideo.src = window.URL.createObjectURL(stream);
            }
            _this.thisVideo.onloadedmetadata = function () {
              _this.thisVideo.play();
            };
          })
          .catch((err) => {
            console.log(err);
            this.$message({
              message: "没有开启摄像头权限或浏览器版本不兼容",
              type: "warning",
            });
          });
      });
    },
    photographBtn() {
      // 点击，canvas画图
      this.thisContext.drawImage(
        this.thisVideo,
        0,
        0,
        this.videoWidth,
        this.videoHeight
      );
      // 获取图片base64链接 >>> 这里是base64格式的图片
      this.imgSrc = this.thisCancas.toDataURL("image/png");
    },
    //清空画布
    clearCanvas(id) {
      let c = document.getElementById(id);
      let cxt = c.getContext("2d");
      cxt.clearRect(0, 0, c.width, c.height);
    },
    //重置画布
    resetBtn() {
      this.imgSrc = "";
      this.clearCanvas("canvasCamera");
    },
    //关闭摄像头
    stopCamera() {
      if (this.thisVideo && this.thisVideo !== null) {
        this.thisVideo.srcObject.getTracks()[0].stop();
        this.os = true; //切换成打开摄像头
      }
    },
  sendFocus () {
    console.log('sendFocus')
    var http = axios.create({
            baseURL: "^/api", 
            timeout: 30000,
            headers: {"Content-Type": "application/json"}  
        });
        let url = "/api/focus"; 
        var ip = this.global.ip
        http.post(ip + url, {
            userName: this.userName,
            notplay: this.global.focus,            
            play: this.global.unfocus
        })
        .then(response => {  
            console.log('focus: ' + this.global.focus)
            console.log('unfocus: ' + this.global.unfocus)
            if(this.global.focus < this.global.unfocus){
              this.showWarn = true
            }
            this.global.focus = 1
            this.global.unfocus = 0
            console.log(response.data);
        })
        .catch(error => {
            this.global.focus = 1
            this.global.unfocus = 0
            console.log('Error:', error);
            if (error.response) {
            console.log('Response data:', error.response.data);}
        });
  },
  getNextWord () {
    if (this.wordUnit.length && this.unitPointer < this.wordUnit.length) {
      const word = this.wordUnit[this.unitPointer]
      // console.log(word.type)
      if (word.type === 'new') this.showZh = false
      else this.showZh = false
      this.wordType = word.type
      this.wordEn = word.wordEn
      this.wordZh = word.wordZh
      this.unitPointer += 1
      this.setStatusNums() // 每次切换下一个词都调用这个比较费资源，临时解决方案
    } else if (this.wordUnit.length) {
      this.getNextUnit()
    } else {
      this.showZh = false
      this.wordType = ''
      this.wordEn = '你已经完成当天任务啦'
      this.wordZh = ''
      this.unitPointer = 0
      this.setStatusNums()
    }
    // us.getLearned().then(learned => console.log(this.wordEn, learned[this.wordEn])) // beta版测试用
  },
  getNextUnit () {
    cn.getNextUnitFromList(this.wordList).then((unit) => {
      this.unitPointer = 0
      this.wordUnit = unit
      this.getNextWord()
    }).catch(err => console.log(err))
  },
  learnCurrentWord () {
    if (!this.showZh) return
    if (this.wordType !== 'new') return
    this.xzda = true
    this.dengdai = false
    this.wait = false
    cn.learnWordFromList(this.wordEn, this.wordList).then(() => {
      this.getNextWord()
    }).catch(err => console.log(err))
  },
  reviseCurrentWord (knowType) {
    if (!this.showZh) return
    if (this.wordType !== 'learned') return
    cn.reviseWordFromLearned(this.wordEn, knowType, 'learn').then(() => {
      this.getNextWord()
    }).catch(err => console.log(err))
  },
  setStatusNums () {
    cn.getListLearningStatus(this.wordList).then((res) => {
      this.wordReview = res.wordReview
      this.wordFinished = res.wordFinished
      this.wordLeft = this.wordTotalNum - this.wordReview - this.wordFinished
    }).catch(err => console.log(err))
  },
  cardClicked () {
    this.showZh = !this.showZh
    this.xzda = false
    this.dengdai = true
    this.wait = false
    setTimeout(() => {
      this.xzda = false
      this.dengdai = false
      this.wait=true
    }, 3000);
  },
  goBack () {
    clearInterval(this.global.sendfocus);
    clearInterval(this.global.sendcamera);
    this.stopCamera()
    this.global.sendfocus = 0
    this.global.sendcamera = 0
    this.$router.go(-1)
  },
  setUserName(){
    cn.getUserName().then((res) => {
      this.userName = res
    }).catch(err => console.log(err))
  }
}
}
</script>

<style scoped>
#canvasCamera{
  margin-left: 20px;
}
.box1{
  background:rgba(249,93,62,0.1)
}
.canvas {
  display: none;/* xujiawei是大神*/
}
.learn {
width: 100vw;
height: 100vh;
background: #F0F0F0;
}

.main {
height: 100%;
max-width: 1300px;
margin: 0 auto;
position: relative;
}

.main-left {
width: 220px;
background: #FFFFFF;
position: absolute;
left: 0;
top: 80px;
bottom: 0;
box-shadow: 4px 0 18px 0 rgba(0,0,0,.28);
}

.left-back {
width: 100%;
height: 55px;
padding: 0 20px;
box-sizing: border-box;
border-bottom: 1px solid #f0f0f0;
display: flex;
align-items: center;
font-size: 14px;
letter-spacing: 1.5px;
color: #455358;
font-weight: 600;
cursor: pointer;
}

.left-back img {
width: 16px;
height: 16px;
margin-right: 7px;
margin-top: 2px;
}

.left-main {
width: 100%;
padding-top: 30px;
display: flex;
flex-direction: column;
}

.left-title {
display: flex;
height: 50px;
align-items: center;
font-size: 14px;
letter-spacing: 1.5px;
font-weight: 600;
color: #455358;
padding: 0 20px;
box-sizing: border-box;
}

.left-title img {
width: 28px;
height: 28px;
margin-right: 4px;
}

.left-counter {
width: 100%;
height: 400px;
display: flex;
flex-direction: column;
align-items: center;
justify-content: space-between;
margin-top: 50px;
}

.left-number {
color: #455358;
font-weight: 700;
font-size: 20px;
}

.left-counter span {
color: #455358;
font-size: 12px;
font-weight: 600;
}

.left-counter img {
width: 28px;
height: 28px;
}

.left-rate {
position: absolute;
bottom: 0;
height: 80px;
width: 100%;
display: flex;
align-items: center;
justify-content: center;
color: #455358;
font-size: 20px;
font-weight: bolder;
}

.learn-word {
position: absolute;
left: 220px;
right: 0;
top: 80px;
bottom: 0;
padding: 30px;
box-sizing: border-box;
}

.word-card {
width: 100%;
height: 75%;
background: #FFFFFF;
position: relative;
cursor: pointer;
}

.card-progress {
position: absolute;
top: 0;
width: 100%;
height: 5px;
background: rgb(128, 209, 185);
}

.card-progress div {
height: 100%;
background: #40BC96;
transition: all 0.2s;
}

.word-en,
.word-zh {
width: 100%;
display: flex;
align-items: center;
justify-content: center;
flex-direction: column;
left: 0;
color: #455358;
}

.word-zh {
height: calc(64% - 100px);
margin: 50px 0;
font-size: 23px;
line-height: 30px;
padding: 0 18%;
overflow-x: hidden;
overflow-y: auto;
box-sizing: border-box;
font-family: "Microsoft YaHei" !important;
text-align: left;
align-items: center;
justify-content: flex-start;
white-space: pre-line;
}

.word-en {
font-size: 26px;
height: 36%;
font-family: TimesNewRoman !important;
}

.word-en div {
width: 100%;
height: 80%;
}

.word-en span {
width: 100%;
text-align: center;
flex-shrink: 0;
}

.word-choice {
width: 100%;
height: 72px;
margin-top: 40px;
display: flex;
align-items: center;
justify-content: space-between;
padding-left: 5px;
box-sizing: border-box;
}

.button {
width: 30%;
height: 100%;
display: flex;
align-items: center;
justify-content: center;
font-size: 19px;
font-weight: 700;
letter-spacing: 1px;
cursor: pointer;
position: relative;
transition: all 0.4s ease;
}

.new {
width: 100%;
border: solid 2px #3CCFCF;
color: #455358;
}

.green {
border: solid 2px #90c0ac;
color: #90c0ac;
}

.yellow {
border: solid 2px #e0a143;
color: #e0a143;
}

.red {
border: solid 2px #cd6c48;
color: #cd6c48;
}

.button-num {
width: 20px;
height: 20px;
position: absolute;
left: -10px;
top: -4px;
background: #F0F0F0;
padding: 3px 2px;
}

.button-num span {
width: 100%;
height: 100%;
border-radius: 50%;
border: 2px solid #c0cace;
box-sizing: border-box;
color: #c0cace;
display: flex;
align-items: center;
justify-content: center;
font-size: 14px;
font-weight: 700;
}
</style>
